﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Onix21Ref = www.editeur.org.onix.Item2.Item1.reference;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Collections;

namespace LinqBasics
{
    class Program
    {
        static void Main(string[] args)
        {                       
            try
            {
                String onixMessage = System.IO.File.ReadAllText(@"C:\Onix\BritishComputerSociety20110510031135.xml");

                onixMessage = onixMessage.Replace("http://www.editeur.org/onix/2.1/01/short/onix-international.dtd",
                    @"C:\Onix\Files\21\ShortDTD\onix-international.dtd");
                onixMessage = onixMessage.Replace("http://www.editeur.org/onix/2.1/02/short/onix-international.dtd",
                    @"C:\Onix\Files\21\ShortDTD\onix-international.dtd");
                onixMessage = onixMessage.Replace("http://www.editeur.org/onix/2.1/03/short/onix-international.dtd",
                    @"C:\Onix\Files\21\ShortDTD\onix-international.dtd");

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(onixMessage);
                
                string referenceOnix;

                using (MemoryStream memStream = new MemoryStream())
                {
                    XmlWriter xmlWriter = XmlWriter.Create(memStream);
                    XslCompiledTransform transform = new XslCompiledTransform();
                    XsltSettings settings = new XsltSettings();
                    settings.EnableScript = true;
                    transform.Load(@"C:\Onix\OnixTaggedName.xsl");
                    transform.Transform(xmlDoc, xmlWriter);
                    memStream.Position = 0;
                    using (StreamReader sr = new StreamReader(memStream))
                    {
                        referenceOnix = sr.ReadToEnd();
                    }
                }

                referenceOnix = referenceOnix.Remove(0, referenceOnix.IndexOf("<Header>"));

                string referenceXSDHeader =
                    @"<?xml version='1.0' encoding='utf-8'?>
						<ONIXMessage xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
						xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
						xmlns='http://www.editeur.org/onix/2.1/reference'>";

                referenceOnix = referenceXSDHeader + referenceOnix;

                Onix21Ref.XRoot root = Onix21Ref.XRoot.Load(XmlReader.Create(new StringReader(referenceOnix)));
                
                //StringBuilder onixDetails = new StringBuilder();

                List<Product> products = new List<Product>();

                foreach (Onix21Ref.Product product in root.ONIXMessage.Product)
                {
                    Product prod = new Product();
                    prod.Prices = new List<Price>();

                    //onixDetails.AppendLine(product.Title[0].TitleText.TypedValue);
                    prod.Title = product.Title[0].TitleText.TypedValue;

                    if (product.Title[0].Subtitle != null)
                    {
                        if (!String.IsNullOrWhiteSpace(product.Title[0].Subtitle.TypedValue))
                        {
                            //onixDetails.AppendLine(product.Title[0].Subtitle.TypedValue);
                            prod.Title = prod.Title + " " + product.Title[0].Subtitle.TypedValue;
                        }
                    }
                    
                    foreach (Onix21Ref.ProductIdentifier pi in product.ProductIdentifier)
                    {
                        if (pi.ProductIDType.TypedValue.Equals("15"))
                        {
                            //onixDetails.AppendLine(pi.IDValue.TypedValue);
                            prod.ISBN = Int64.Parse(pi.IDValue.TypedValue);
                        }
                    }

                    foreach (Onix21Ref.SupplyDetail sd in product.SupplyDetail)
                    {
                        foreach (Onix21Ref.SupplierName sn in sd.SupplierName)
                        {
                            if (sn == null) continue;

                            if (sn.TypedValue.Equals("Turpin Distribution Services"))
                            {
                                foreach (Onix21Ref.Price price in sd.Price)
                                {

                                    String amount;

                                    //onixDetails.AppendLine(price.CurrencyCode.TypedValue);

                                    if (price.PriceQualifier != null)
                                    {
                                        if (price.PriceQualifier.TypedValue.Equals("01"))
                                        {
                                            //onixDetails.AppendLine(String.Format("Member/subscriber price - {0}", price.PriceAmount.TypedValue));
                                            amount = String.Format("Member/subscriber price - {0}", price.PriceAmount.TypedValue);
                                        }
                                        else
                                        {
                                            //onixDetails.AppendLine(price.PriceAmount.TypedValue);
                                            amount = price.PriceAmount.TypedValue;
                                        }
                                    }
                                    else
                                    {
                                        //onixDetails.AppendLine(price.PriceAmount.TypedValue);
                                        amount = price.PriceAmount.TypedValue;
                                    }
                                    
                                    prod.Prices.Add(new Price() { Currency = price.CurrencyCode.TypedValue, Amount = amount });                                                                        
                                }                               
                            }
                        }
                    }

                    //onixDetails.AppendLine();
                    //onixDetails.AppendLine();
                    //onixDetails.AppendLine();

                    products.Add(prod);
                }

                List<Product> prods = products.Where(x => x.Prices.Count > 0).ToList();

                IOrderedEnumerable<Product> prods2 = prods.OrderBy(x => x.ISBN);

                //Console.WriteLine(onixDetails.ToString());


                StringBuilder onixDetails2 = new StringBuilder();

                foreach (Product p in prods2)
                {
                    onixDetails2.Append(p.ISBN);
                    onixDetails2.Append(";");

                    onixDetails2.Append(p.Title);
                    onixDetails2.Append(";");

                    foreach (Price price in p.Prices)
                    {
                        onixDetails2.Append(price.Currency);
                        onixDetails2.Append(";");
                        onixDetails2.Append(price.Amount);
                        onixDetails2.Append(";");
                    }

                    onixDetails2.AppendLine();
                }

                
                File.WriteAllText(@"C:\Onix\BCS.txt", onixDetails2.ToString());

                //Console.ReadLine();                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }

            
            

        }
    }

    class Product : IComparer
    {
        public String Title { get; set; }
        public Int64 ISBN { get; set; }
        public List<Price> Prices { get; set; }

        public int Compare(object x, object y)
        {
            Int64 a = (Int64)x;
            Int64 b = (Int64)y;

            if (a > b)
            {
                return 1;
            }

            if (b > a)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }

    class Price
    {
        public String Currency { get; set; }
        public String Amount { get; set; }
    }


}
